import store from "../store";
import db from "../../datastore";
import mqtt from "mqtt";

let clientId =
  "mqttjs_" +
  Math.random()
    .toString(16)
    .substr(2, 8);
var client;
const options = {
  reconnectPeriod: 1000, // 1000毫秒，两次重新连接之间的间隔
  connectTimeout: 40000, // 40 * 1000毫秒，等待收到CONNACK的时间
  clientId: clientId,
  username: "serverclient",
  password: "serverpass",
  clean: true,
};

var wskurl = db
  .read()
  .get("trades.mqttUrl")
  .value();
let loginData = null;
function initWebSocket(id, url, data, callback) {
  try {
    client.end();
  } catch (e) {}
  // ws://hz.tjanta.com:8001/mqtt
  client = mqtt.connect(wskurl.wsMqtt_hz, options);
  console.log(options);
  client.on("connect", (e) => {
    console.log("连接成1功--k线");
    wsOnOpen();
  });
  // 接收消息处理
  client.on("message", (topic, message) => {
    wsOnMessage(message.toString(),topic);
  });
  // 断开发起重连
  client.on("reconnect", (error) => {
    console.log("正在1重连:", error);
  });
  // 链接异常处理
  client.on("error", (error) => {
    console.log("连接1失败:", error);
  });
}

// WebSocket打开回调
function wsOnOpen(e) {}

// 订阅

function subscribe(name) {
  console.log(name);
  client.subscribe(name, { qos: 2 });
}

function unsubscribe(name) {
  console.log(name);
  client.unsubscribe(name, { qos: 2 });
}

let isHostory = false
// 发送WebSocket请求
function wsSend(name) {
  console.log(name);
  let topicArr = name.split(';')
  if(topicArr[4]){
    isHostory = true
  }else{
    isHostory = false
  }
  client.publish("kxian/weituo", name, { qos: 0 });
}

// 接收WebSocket返回信息
function wsOnMessage(data,topic) {
  if(isHostory){
    store.dispatch("product/historyKline", data);
  }else{
    store.dispatch("product/updateKLines", data);
  }
}

// WebSocket关闭回调
function wsClose() {}

export {
  wsClose,
  initWebSocket,
  subscribe,
  unsubscribe,
  wsSend,
  clientId,
  wsOnMessage,
};
